// ===== 主要JavaScript功能 =====

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
    initCountdown();
    initParticleEffects();
    initFloatingPetals();
});

// 应用初始化
function initializeApp() {
    initNavigation();
    initScrollEffects();
    initAOS();
    initParallaxEffects();
    initTypewriterEffects();
    initScrollProgress();
    initSmoothScroll();
    initMobileOptimizations();

    console.log('十年之约网站已加载完成 💕');
}

// 导航栏功能
function initNavigation() {
    const navToggle = document.querySelector('.nav-toggle');
    const navMenu = document.querySelector('.nav-menu');
    const navLinks = document.querySelectorAll('.nav-menu a');
    const navContainer = document.querySelector('.nav-container');

    // 移动端菜单切换
    if (navToggle) {
        navToggle.addEventListener('click', function() {
            navMenu.classList.toggle('active');
            navToggle.classList.toggle('active');
        });
    }

    // 点击导航链接后关闭移动端菜单
    navLinks.forEach(link => {
        link.addEventListener('click', function() {
            navMenu.classList.remove('active');
            navToggle.classList.remove('active');
        });
    });

    // 滚动时导航栏样式变化
    window.addEventListener('scroll', function() {
        if (window.scrollY > 100) {
            navContainer.classList.add('scrolled');
        } else {
            navContainer.classList.remove('scrolled');
        }
    });

    // 高亮当前页面section
    updateActiveNavLink();
    window.addEventListener('scroll', updateActiveNavLink);
}

// 更新活动导航链接
function updateActiveNavLink() {
    const sections = document.querySelectorAll('section[id]');
    const navLinks = document.querySelectorAll('.nav-menu a');

    let currentSection = '';
    const scrollPosition = window.scrollY + 200;

    sections.forEach(section => {
        const sectionTop = section.offsetTop;
        const sectionHeight = section.offsetHeight;

        if (scrollPosition >= sectionTop && scrollPosition < sectionTop + sectionHeight) {
            currentSection = section.getAttribute('id');
        }
    });

    navLinks.forEach(link => {
        link.classList.remove('active');
        if (link.getAttribute('href') === `#${currentSection}`) {
            link.classList.add('active');
        }
    });
}

// 滚动效果
function initScrollEffects() {
    // 添加滚动触发动画
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const scrollObserver = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('scrolled-into-view');
            }
        });
    }, observerOptions);

    // 观察所有卡片元素
    const animatedElements = document.querySelectorAll('.text-card, .flow-card, .dream-category, .timeline-item');
    animatedElements.forEach(el => {
        scrollObserver.observe(el);
    });
}

// 初始化AOS动画库
function initAOS() {
    if (typeof AOS !== 'undefined') {
        AOS.init({
            duration: 1000,
            once: true,
            offset: 100,
            easing: 'ease-out-quart',
            disable: window.innerWidth < 768 ? 'mobile' : false
        });
    }
}

// 视差滚动效果
function initParallaxEffects() {
    window.addEventListener('scroll', function() {
        const scrolled = window.pageYOffset;

        // 英雄区域视差效果
        const heroContent = document.querySelector('.hero-content');
        if (heroContent) {
            const speed = 0.5;
            heroContent.style.transform = `translateY(${scrolled * speed}px)`;
        }

        // 花瓣飘落视差效果
        const petals = document.querySelector('.floating-petals');
        if (petals) {
            const speed = 0.3;
            petals.style.transform = `translateY(${scrolled * speed}px)`;
        }
    });
}

// 打字机效果
function initTypewriterEffects() {
    const typewriterElements = document.querySelectorAll('.typewriter');

    typewriterElements.forEach(element => {
        const text = element.textContent;
        element.textContent = '';
        element.style.opacity = '1';

        let i = 0;
        const typeSpeed = 50;

        function typeWriter() {
            if (i < text.length) {
                element.textContent += text.charAt(i);
                i++;
                setTimeout(typeWriter, typeSpeed);
            }
        }

        // 延迟开始打字效果
        setTimeout(typeWriter, 1000);
    });
}

// 滚动进度条
function initScrollProgress() {
    const progressBar = document.createElement('div');
    progressBar.className = 'scroll-progress';
    progressBar.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 0%;
        height: 3px;
        background: linear-gradient(90deg, var(--accent-color), var(--emphasis-color));
        z-index: 9999;
        transition: width 0.3s ease;
    `;
    document.body.appendChild(progressBar);

    window.addEventListener('scroll', function() {
        const windowHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
        const scrolled = (window.scrollY / windowHeight) * 100;
        progressBar.style.width = scrolled + '%';
    });
}

// 平滑滚动
function initSmoothScroll() {
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();

            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);

            if (targetElement) {
                const targetPosition = targetElement.offsetTop - 80;

                window.scrollTo({
                    top: targetPosition,
                    behavior: 'smooth'
                });
            }
        });
    });
}

// 移动端优化
function initMobileOptimizations() {
    // 触摸设备检测
    const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;

    if (isTouchDevice) {
        document.body.classList.add('touch-device');

        // 移除hover效果在触摸设备上
        const style = document.createElement('style');
        style.textContent = `
            .touch-device .text-card:hover,
            .touch-device .flow-card:hover,
            .touch-device .dream-category:hover {
                transform: none !important;
            }
        `;
        document.head.appendChild(style);
    }

    // 防止iOS缩放
    document.addEventListener('gesturestart', function(e) {
        e.preventDefault();
    });

    // 处理横竖屏切换
    window.addEventListener('orientationchange', function() {
        setTimeout(function() {
            window.scrollTo(0, 0);
        }, 100);
    });
}

// 动态添加浮动花瓣
function createFloatingPetal() {
    const petalsContainer = document.querySelector('.floating-petals');
    if (!petalsContainer) return;

    const petal = document.createElement('div');
    petal.innerHTML = '🌸';
    petal.style.cssText = `
        position: absolute;
        left: ${Math.random() * 100}%;
        top: -50px;
        font-size: ${Math.random() * 1.5 + 1}rem;
        opacity: ${Math.random() * 0.6 + 0.2};
        animation: fall ${Math.random() * 5 + 10}s linear infinite;
        pointer-events: none;
        z-index: 1;
    `;

    petalsContainer.appendChild(petal);

    // 动画结束后移除花瓣
    setTimeout(() => {
        petal.remove();
    }, 15000);
}

// 定期创建新的花瓣
setInterval(createFloatingPetal, 3000);

// 添加花瓣下落动画
const style = document.createElement('style');
style.textContent = `
    @keyframes fall {
        0% {
            transform: translateY(-50px) rotate(0deg);
            opacity: 0;
        }
        10% {
            opacity: 1;
        }
        90% {
            opacity: 1;
        }
        100% {
            transform: translateY(100vh) rotate(360deg);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);

// 添加粒子效果
function createParticle(x, y) {
    const particle = document.createElement('div');
    particle.className = 'particle';
    particle.style.cssText = `
        left: ${x}px;
        top: ${y}px;
        width: ${Math.random() * 8 + 4}px;
        height: ${Math.random() * 8 + 4}px;
        animation: particleFloat ${Math.random() * 5 + 5}s ease-in-out;
    `;

    document.body.appendChild(particle);

    setTimeout(() => {
        particle.remove();
    }, 10000);
}

// 鼠标移动时创建粒子效果
document.addEventListener('mousemove', function(e) {
    if (Math.random() > 0.98) {
        createParticle(e.clientX, e.clientY);
    }
});

// 添加CSS变量动态更新
function updateCSSVariables() {
    const root = document.documentElement;

    // 根据滚动位置更新颜色强度
    window.addEventListener('scroll', function() {
        const scrollPercent = window.scrollY / (document.documentElement.scrollHeight - window.innerHeight);
        const accentIntensity = 1 - (scrollPercent * 0.3);

        root.style.setProperty('--accent-opacity', accentIntensity);
    });
}

updateCSSVariables();

// 错误处理
window.addEventListener('error', function(e) {
    console.error('网站运行错误:', e.error);
});

// 性能监控
function logPerformance() {
    if ('performance' in window) {
        window.addEventListener('load', function() {
            setTimeout(function() {
                const perfData = performance.getEntriesByType('navigation')[0];
                console.log('页面加载时间:', perfData.loadEventEnd - perfData.loadEventStart, 'ms');
            }, 0);
        });
    }
}

logPerformance();

// 添加键盘导航支持
document.addEventListener('keydown', function(e) {
    // ESC键关闭移动端菜单
    if (e.key === 'Escape') {
        const navMenu = document.querySelector('.nav-menu');
        const navToggle = document.querySelector('.nav-toggle');

        if (navMenu && navMenu.classList.contains('active')) {
            navMenu.classList.remove('active');
            navToggle.classList.remove('active');
        }
    }

    // 方向键导航
    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
        const sections = document.querySelectorAll('section[id]');
        const currentSection = document.querySelector('section[id].scrolled-into-view');

        let targetIndex = 0;
        sections.forEach((section, index) => {
            if (section === currentSection) {
                targetIndex = e.key === 'ArrowDown' ? index + 1 : index - 1;
            }
        });

        if (targetIndex >= 0 && targetIndex < sections.length) {
            const targetSection = sections[targetIndex];
            const targetPosition = targetSection.offsetTop - 80;

            window.scrollTo({
                top: targetPosition,
                behavior: 'smooth'
            });
        }
    }
});

// 添加页面可见性API支持
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        // 页面隐藏时暂停音乐和动画
        pauseAnimations();
    } else {
        // 页面显示时恢复动画
        resumeAnimations();
    }
});

function pauseAnimations() {
    // 暂停CSS动画
    document.querySelectorAll('*').forEach(el => {
        el.style.animationPlayState = 'paused';
    });
}

function resumeAnimations() {
    // 恢复CSS动画
    document.querySelectorAll('*').forEach(el => {
        el.style.animationPlayState = 'running';
    });
}

// ===== 倒计时功能 =====
function initCountdown() {
    // 设置目标日期：2025年10月26日 11:21
    const targetDate = new Date('2025-10-26T11:21:00');

    // 更新倒计时
    function updateCountdown() {
        const now = new Date().getTime();
        const distance = targetDate - now;

        if (distance < 0) {
            // 倒计时结束
            document.getElementById('days').textContent = '00';
            document.getElementById('hours').textContent = '00';
            document.getElementById('minutes').textContent = '00';
            document.getElementById('seconds').textContent = '00';

            // 显示完成消息
            showCountdownComplete();
            return;
        }

        const days = Math.floor(distance / (1000 * 60 * 60 * 24));
        const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((distance % (1000 * 60)) / 1000);

        document.getElementById('days').textContent = padZero(days);
        document.getElementById('hours').textContent = padZero(hours);
        document.getElementById('minutes').textContent = padZero(minutes);
        document.getElementById('seconds').textContent = padZero(seconds);
    }

    function padZero(num) {
        return num < 10 ? '0' + num : num;
    }

    function showCountdownComplete() {
        const countdownDisplay = document.querySelector('.countdown-display');
        if (countdownDisplay) {
            countdownDisplay.innerHTML = `
                <div style="grid-column: 1 / -1; text-align: center;">
                    <div style="font-size: 3rem; margin-bottom: 1rem;">
                        🎉 相见时刻到了！🎉
                    </div>
                    <div style="font-size: 1.5rem; color: var(--romantic-pink);">
                        期待美好的相见！
                    </div>
                </div>
            `;
            createCelebrationEffect();
        }
    }

    // 立即更新一次，然后每秒更新
    updateCountdown();
    setInterval(updateCountdown, 1000);
}

// ===== 粒子效果 =====
function initParticleEffects() {
    const particleField = document.getElementById('particleField');
    if (!particleField) return;

    function createParticle() {
        const particle = document.createElement('div');
        particle.className = 'particle';

        // 随机大小和位置
        const size = Math.random() * 6 + 2;
        particle.style.width = size + 'px';
        particle.style.height = size + 'px';
        particle.style.left = Math.random() * 100 + '%';

        // 随机动画持续时间
        const duration = Math.random() * 10 + 5;
        particle.style.animationDuration = duration + 's';

        particleField.appendChild(particle);

        // 动画结束后移除粒子
        setTimeout(() => {
            particle.remove();
        }, duration * 1000);
    }

    // 定期创建新粒子
    setInterval(createParticle, 800);

    // 初始创建一些粒子
    for (let i = 0; i < 10; i++) {
        setTimeout(createParticle, i * 100);
    }
}

// ===== 浮动花瓣效果 =====
function initFloatingPetals() {
    const petalsContainer = document.getElementById('petalsContainer');
    if (!petalsContainer) return;

    const petals = ['🌸', '🌺', '🌷', '🌹', '💮', '🏵️'];

    function createPetal() {
        const petal = document.createElement('div');
        petal.className = 'floating-petal';
        petal.textContent = petals[Math.floor(Math.random() * petals.length)];

        // 随机位置和大小
        petal.style.left = Math.random() * 100 + '%';
        petal.style.fontSize = (Math.random() * 1.5 + 1) + 'rem';

        // 随机动画持续时间和延迟
        const duration = Math.random() * 10 + 10;
        petal.style.animationDuration = duration + 's';

        petalsContainer.appendChild(petal);

        // 动画结束后移除花瓣
        setTimeout(() => {
            petal.remove();
        }, duration * 1000);
    }

    // 定期创建新花瓣
    setInterval(createPetal, 3000);

    // 初始创建一些花瓣
    for (let i = 0; i < 5; i++) {
        setTimeout(createPetal, i * 800);
    }
}

// ===== 庆祝效果 =====
function createCelebrationEffect() {
    const celebrationEmojis = ['❤️', '💕', '💖', '💗', '💝', '🎉', '✨', '🌟'];

    for (let i = 0; i < 30; i++) {
        setTimeout(() => {
            const celebration = document.createElement('div');
            celebration.textContent = celebrationEmojis[Math.floor(Math.random() * celebrationEmojis.length)];
            celebration.style.cssText = `
                position: fixed;
                left: ${Math.random() * 100}%;
                top: -50px;
                font-size: ${Math.random() * 2 + 1}rem;
                z-index: 10000;
                animation: celebrationFall 3s ease-in-out;
                pointer-events: none;
            `;

            document.body.appendChild(celebration);

            setTimeout(() => {
                celebration.remove();
            }, 3000);
        }, i * 100);
    }

    // 添加庆祝动画样式
    const style = document.createElement('style');
    style.textContent = `
        @keyframes celebrationFall {
            0% {
                transform: translateY(-50px) rotate(0deg);
                opacity: 0;
            }
            10% {
                opacity: 1;
            }
            90% {
                opacity: 1;
            }
            100% {
                transform: translateY(100vh) rotate(360deg);
                opacity: 0;
            }
        }
    `;
    document.head.appendChild(style);
}

// ===== SVG动画增强 =====
function initSVGAnimations() {
    // 为SVG元素添加悬停效果
    const svgElements = document.querySelectorAll('svg');
    svgElements.forEach(svg => {
        svg.addEventListener('mouseenter', function() {
            this.style.transform = 'scale(1.05)';
            this.style.transition = 'transform 0.3s ease';
        });

        svg.addEventListener('mouseleave', function() {
            this.style.transform = 'scale(1)';
        });
    });
}

// ===== 页面滚动时的视差效果 =====
function initParallaxEffects() {
    window.addEventListener('scroll', function() {
        const scrolled = window.pageYOffset;

        // 背景视差效果
        const romanticBg = document.querySelector('.romantic-bg');
        if (romanticBg) {
            romanticBg.style.transform = `translateY(${scrolled * 0.5}px)`;
        }

        // 粒子场视差效果
        const particleField = document.getElementById('particleField');
        if (particleField) {
            particleField.style.transform = `translateY(${scrolled * 0.3}px)`;
        }

        // 花瓣视差效果
        const petalsContainer = document.getElementById('petalsContainer');
        if (petalsContainer) {
            petalsContainer.style.transform = `translateY(${scrolled * 0.2}px)`;
        }

        // 英雄区域视差效果
        const heroContent = document.querySelector('.hero-content');
        if (heroContent) {
            const speed = 0.5;
            heroContent.style.transform = `translateY(${scrolled * speed}px)`;
        }
    });
}

// 导出函数供其他脚本使用
window.TenYearsLove = {
    createParticle,
    createFloatingPetal,
    updateActiveNavLink,
    createCelebrationEffect,
    initCountdown,
    initParticleEffects,
    initFloatingPetals
};